module.exports = (app) => {
  const express = require('express')
  const router = express.Router()
  const Course = require('../../models/Course')
  const Category = require('../../models/Category')
  const Classroom = require('../../models/Classroom')
  const Topic = require('../../models/Topic')
  const Tag = require('../../models/Tag')
  const Group = require('../../models/Group')
  const User = require('../../models/User')
  const jwt = require('jsonwebtoken')

  // 获取热门课程
  router.get('/hotcourses', async (req, res) => {
    const hotCourses = await Course.aggregate([
      { $sort: { readed: -1 } },
      { $limit: 6 }
    ])
    res.send(hotCourses)
  })

  /**
   * 获取精品课程
   * 1.分类：精品推荐 特价好课 前六个次级分类
   * 2.每个分类 7 门课
   * */

  // 获取 精品课程下的分类
  router.get('/goodcourses/navlist', async (req, res) => {
    const parentCate = await Category.aggregate([{ $match: { name: '课程' } }])
    const parentCateId = parentCate[0]._id
    const secCategory = await Category.aggregate([
      { $match: { parent: parentCateId } },
      { $limit: 6 }
    ])
    let secCategories = secCategory.map((v) => {
      return {
        name: v.name,
        id: v._id
      }
    })
    secCategories.unshift({
      name: '特价好课',
      id: '222222aaaaa2222222'
    })
    secCategories.unshift({
      name: '精品推荐',
      id: '111111vvvvvv1111111'
    })
    res.send(secCategories)
  })

  // 获取精品推荐和特价好课
  router.get('/goodcourses', async (req, res) => {
    const parentCate = await Category.aggregate([{ $match: { name: '课程' } }])
    const parentCateId = parentCate[0]._id
    const secCategory = await Category.aggregate([
      { $match: { parent: parentCateId } },
      { $limit: 6 }
    ])
    const secCategories = secCategory.map((item) => item._id)
    const childCategory = await Category.aggregate([
      { $match: { parent: { $in: secCategories } } }
    ])
    const childCategories = childCategory.map((item) => item._id)

    // 精品好课
    const goodCourses = await Course.aggregate([
      { $match: { category: { $in: childCategories } } },
      { $sort: { students: -1 } },
      { $limit: 7 }
    ])

    // 特价好课
    const priceCourses = await Course.aggregate([
      {
        $match: {
          category: { $in: childCategories },
          price: { $gt: 0, $lte: 100 },
          readed: { $gt: 10000 }
        }
      },
      { $sort: { students: -1 } },
      { $limit: 7 }
    ])

    const courses = [
      { name: '精品好课', coursesList: goodCourses },
      { name: '特价好课', coursesList: priceCourses }
    ]

    res.send(courses)
  })

  // 通过传递 id 获取 对应分类下的7个课程
  router.get('/goodcourses/:id', async (req, res) => {
    const category = await Category.findOne({ _id: req.params.id })
    const childCategories = await Category.find({ parent: category._id })
    const childCategoriesArr = childCategories.map((v) => v._id)
    const courses = await Course.aggregate([
      { $match: { category: { $in: childCategoriesArr } } },
      { $sort: { students: -1 } },
      { $limit: 7 }
    ])
    res.send(courses)
  })

  // 获取二级分类，头部添加 "全部" 分类
  router.get('/course/categories', async (req, res) => {
    const Parentcategories = await Category.findOne({ name: '课程' })
    const categories = await Category.find({
      parent: Parentcategories._id
    }).lean()
    categories.unshift({
      _id: '5555555aaa5555555',
      name: '全部',
      parent: Parentcategories._id
    })
    res.send(categories)
  })

  // 获取所有课程
  router.get('/course/allcourse', async (req, res) => {
    const allCourses = await Course.aggregate([{ $sort: { readed: -1 } }])
    res.send(allCourses)
  })

  // 获取二级分类下的子分类
  router.get('/course/childcategories/:id', async (req, res) => {
    const parentCate = await Category.findOne({ _id: req.params.id })
    const childCategories = await Category.find({ parent: parentCate._id })
    childCategories.unshift({
      parent: parentCate._id,
      name: '全部',
      _id: '444444bbb444444'
    })
    res.send(childCategories)
  })

  // 根据二级分类获取课程
  router.get('/course/getcoursesbysecid/:id', async (req, res) => {
    const parentCate = await Category.findOne({ _id: req.params.id })
    const childCategories = await Category.find({ parent: parentCate._id })
    const childCategoriesArr = childCategories.map((v) => v._id)
    const courses = await Course.aggregate([
      { $match: { category: { $in: childCategoriesArr } } },
      { $sort: { students: -1 } }
    ])
    res.send(courses)
  })

  // 根据子级分类获取课程
  router.get('/course/getcoursesbychildid/:id', async (req, res) => {
    const category = await Category.findOne({ _id: req.params.id })
    const courses = await Course.aggregate([
      { $match: { category: category._id } },
      { $sort: { students: -1 } }
    ])
    res.send(courses)
  })

  // 获取班级列表
  router.get('/classroom', async (req, res) => {
    const classroomRes = await Classroom.find().lean()
    res.send(classroomRes)
  })

  // 获取话题列表
  router.get('/topic', async (req, res) => {
    const topicRes = await Topic.find().lean()
    res.send(topicRes)
  })

  // 获取标签列表
  router.get('/tag', async (req, res) => {
    const tagsRes = await Tag.find().lean()
    res.send(tagsRes)
  })

  // 获取热门小组
  router.get('/hotgroup', async (req, res) => {
    const hotgroup = await Group.aggregate([{ $sort: { topic: -1 } }])
    const groupData = hotgroup.slice(0, 8)
    res.send(groupData)
  })

  // 获取热门话题
  router.get('/hottopic', async (req, res) => {
    const hotTopic = await Topic.find({ lastReply: { $exists: true } })
    res.send(hotTopic)
  })

  // 获取新晋小组数据
  router.get('/newgroup', async (req, res) => {
    const newGroup = await Group.aggregate([
      { $sort: { number: 1 } },
      { $limit: 3 }
    ])
    res.send(newGroup)
  })

  // 获取所有根据分类的小组的数据
  router.get('/allgroup', async (req, res) => {
    const parentCategory = await Category.findOne({ name: '课程' })
    const categories = await Category.aggregate([
      { $match: { parent: parentCategory._id } },
      {
        $lookup: {
          from: 'groups',
          localField: '_id',
          foreignField: 'category',
          as: 'GroupList'
        }
      }
    ])
    const allgroup = await Group.find({ category: { $exists: true } })
    categories.unshift({
      _id: '3333336666vv22222',
      name: '全部',
      GroupList: allgroup
    })
    res.send(categories)
  })

  // 根据分类id搜索小组数据
  router.get('/searchgroup/:id', async (req, res) => {
    let groupData
    if (req.params.id === '3333336666vv22222') {
      groupData = await Group.find().lean()
    } else {
      const cateId = await Category.findOne({ _id: req.params.id })
      groupData = await Group.find({ category: cateId._id })
    }
    const searchRes = groupData.filter((v) => v.title.includes(req.query.value))
    res.send(searchRes)
  })

  // 登录校验的接口
  router.post('/login', async (req, res) => {
    // 根据用户名找用户
    const { username, password } = req.body
    console.log(username, password)
    const user = await User.findOne({ username })
    // assert(user, 417, '用户不存在')
    if (!user) {
      res.status(422).send({
        message: '用户不存在'
      })
    }
    // 校验密码
    const isValid = require('bcrypt').compareSync(password, user.password)
    console.log(password, user.password)
    console.log(isValid)
    if (!isValid) {
      res.status(422).send({
        message: '密码错误'
      })
    }
    // 返回 token
    const token = jwt.sign({ id: user._id }, 'artoria')
    res.send(token)
  })

  // 用户注册的接口
  router.post('/register', async (req, res) => {
    const user = req.body
    user.tel = user.tel * 1
    const userRes = await User.create(user)
    res.send(user)
  })

  // 获取用户信息
  router.get('/currentuser', async (req, res) => {
    // 通过 token 获取用户信息
    const token = req.headers.authorization.replace('Bearer ', '')
    const userId = jwt.verify(token, 'artoria').id
    const user = await User.findOne({ _id: userId })
    res.send(user)
  })

  // 更新用户信息
  router.post('/updateuserinfo', async (req, res) => {
    const userInfo = req.body
    const newUser = await User.findByIdAndUpdate(userInfo._id, userInfo)
    res.send(newUser)
  })

  // assert 返回的是 HTML 文本，需要对错误统一进行处理
  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send({
      message: err.message
    })
  })

  app.use('/web/api', router)
}
